/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hanuma;

import java.sql.*;
import java.io.*;
import java.util.*;

/**
 *
 * @author niyaz
 */
public class PersistentInBase implements Persistent {

    Connection conn = null;
    Statement stat = null;
    String table;
    private int size = 0;

    public PersistentInBase(String store) {
        table = store;

        try {
            String userName = "root";
            String password = "";
            String url = "jdbc:mysql://127.0.0.1:3306/hanuma";
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url, userName, password);

            if (conn.isValid(1000)) {
                System.out.println("Database connection established");
            }

            stat = conn.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void put(String user) {
        size++;
        try {
            stat.execute("insert into " + table + " values('" + user + "');");
        } catch (Exception e) {
          //  e.printStackTrace();
        }
    }

    public boolean contains(String user) {
        try {
            stat = conn.createStatement();
            ResultSet rez = stat.executeQuery("select mid from " + table + " where mid='" + user+"';");

            if (rez.next()) {
                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return true;
    }

    public int size() {
        return size;
    }

    public UserList getUserList(){
        UserList list = new UserList();
        try {
            stat = conn.createStatement();
            ResultSet rez = stat.executeQuery("select mit from " + table + ";");
            while (rez.next()){

                list.list.add(rez.getString(1));
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return list;
    }

}
